/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import fs from '@ohos.file.fs';
import { hilog } from '@kit.PerformanceAnalysisKit';

export class InputStream {
  public DOMAIN: number = 0x8632;
  public TAG: string = "InputStream";
  public fstat: fs.Stat;
  public fs: fs.File;
  public mBuf: Uint8Array;
  public bOff: number = 0;
  public markOff: number = 0;
  public readLimit: number = 0;

  constructor(buf: Uint8Array) {
    this.mBuf = buf;
  }

  public available(): number {
    hilog.info(this.DOMAIN, this.TAG, `InputStream available ${this.mBuf.length}`);
    return this.mBuf.length;
  }

  public reset() {
    hilog.info(this.DOMAIN, this.TAG, 'reset');
    this.bOff = 0;
  }

  public mark(off: number) {
    hilog.info(this.DOMAIN, this.TAG, `mark: ${off}`);
    this.markOff = this.bOff;
    this.readLimit = off;
  }

  public markSupported(): boolean {
    return true;
  }

  public read(off: number, len: number): Uint8Array {
    hilog.info(this.DOMAIN, this.TAG, `read: off[${off}],len[${len}]`);
    if (this.bOff >= this.mBuf.length - 1 ) {
      hilog.error(this.DOMAIN, this.TAG, `reach the end: bOff[${this.bOff}], len[${this.mBuf.length}]`);
      return null;
    }
    let readLen = len;
    if (this.bOff + len > this.mBuf.length) {
      readLen = this.mBuf.length - this.bOff - 1;
    }
    hilog.info(this.DOMAIN, this.TAG, `read: bOff[${this.bOff}],len[${readLen}]`);
    let desBuf: Uint8Array = new Uint8Array(readLen);
    // desBuf = this.mBuf.copyWithin(off, this.bOff, len);
    desBuf = this.mBuf.slice(this.bOff, len);
    this.bOff += len;
    return desBuf;
  }
}
